from django.views import  View
from django import http
from areas.models import  Area
from django.core.cache import cache

class SubAreasView(View):

    def get(self,request,pk):
        """返回市和区的数据"""
        dict =cache.get('sub_%s'%pk)
        if not dict:
            try:
            # 1.根据id取出省份和市的数据
                #取省份数据
                province_model = Area.objects.get(id=pk)
                # 取市份数据
                sub_list=Area.objects.filter(parent_id=pk)
                # 2.整理市的数据
                list=[]
                for sub in sub_list:
                    list.append({
                        'id':sub.id,
                        'name':sub.name
                    })
                # 3.再整理
                dict ={
                    'id':pk,#pk等同于province_model.id或province_model.pk
                    'name':province_model.name,
                    'subs':list
                }
                cache.set('sub_%s'%pk,dict,3600*24)
            except Exception as e:
                return http.JsonResponse({
                    'code': 400,
                    'errmsg': '获取数据失败'
                })
        # 4.返回json
        return http.JsonResponse({
            'code':0,
            'errmsg':'ok',
            'sub_data':dict
        })





class ProvinceAreasView(View):
    '''返回省份接口数据'''
    def get(self,request):
        list = cache.get('province')
        if not list:
            try:
                # 1.去数据库中查询参数
                province_list =Area.objects.filter(parent__isnull=True)
                # 2.整理省级数据
                list =[]
                for province in province_list:
                    list.append({
                        'id':province.id,
                        'name':province.name
                    })
                cache.set('province',list,3600*24)
            except Exception as e:
                return http.JsonResponse({
                    'code':400,
                    'errmsg':'省份数据错误'
                })
        # 3.返回
        return http.JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'province_list':list
        })